package com.leng.util;

import java.util.ArrayList;
import java.util.List;

public class SqlHelper {
	private  String selectClause;//select部分
	private  String fromClause;//from部分（含join)
	private  String whereClause="";//where子句
	private  String orderbyClause;//ordery子句
	private String limitClause="";//只适用mysql
	
	private List<Object> params = new ArrayList<Object>();//参数
	
	
	
	public SqlHelper(String selectClause, String fromClause, String orderbyClause) {
		super();
		this.selectClause = selectClause;
		this.fromClause = fromClause;
		this.orderbyClause = orderbyClause;
	}
	
	public SqlHelper addCondition(String condition,Object ...params){
		if(whereClause.length()==0){
			whereClause = "where "+condition;
		}else{
			whereClause += " AND "+condition;
		}
		if(null != params && params.length>0){
			for(Object param:params){
				this.params.add(param);
			}
		}
		return this;
	}

	/**
	 *
	 * @param condition
	 * @param start
	 * @param end
	 * @return
	 */
	public  SqlHelper addBetween(String condition,Object start,Object end){
		if(whereClause.length()==0){
			whereClause = "WHERE "+condition;
		}else{
			whereClause += " AND "+condition;
		}
		params.add(start);
		params.add(end);
		return this;
	}

	public String getSelectClause() {
		return selectClause;
	}

	public void setSelectClause(String selectClause) {
		this.selectClause = selectClause;
	}

	public String getFromClause() {
		return fromClause;
	}

	public void setFromClause(String fromClause) {
		this.fromClause = fromClause;
	}

	public String getWhereClause() {
		return whereClause;
	}

	public void setWhereClause(String whereClause) {
		this.whereClause = whereClause;
	}

	public String getOrderbyClause() {
		return orderbyClause;
	}

	public void setOrderbyClause(String orderbyClause) {
		this.orderbyClause = orderbyClause;
	}

	public List<Object> getParams() {
		return params;
	}

	public void setParams(List<Object> params) {
		this.params = params;
	}

	public String getLimitClause() {
		return limitClause;
	}

	public void setLimitClause(String limitClause) {
		this.limitClause = limitClause;
	}
	
	public String getQuery(){
		return this.selectClause+" "+this.fromClause+" "+this.whereClause+" "+this.orderbyClause;
	}
	public String getCountQuery(){
		return "SELECT COUNT(*) "+this.fromClause+" "+this.whereClause;
	}
}
